#!/bin/bash

# 智能启动脚本 - 自动检测Python环境
echo "🚀 启动环境工程咨询API服务器..."

# 进入后端目录
cd backend

# 函数：检测并设置Python环境
setup_python_env() {
    # 1. 检查是否有虚拟环境
    if [ -d "venv" ]; then
        echo "🔧 发现虚拟环境，激活中..."
        source venv/bin/activate
        return 0
    fi

    # 2. 检查conda环境
    if command -v conda &> /dev/null; then
        if conda env list | grep -q "environmental-api"; then
            echo "🔧 发现conda环境，激活中..."
            eval "$(conda shell.bash hook)"
            conda activate environmental-api
            return 0
        else
            echo "⚠️  conda已安装但未找到environmental-api环境"
            echo "创建conda环境: conda create -n environmental-api python=3.11"
            echo "激活环境: conda activate environmental-api"
            echo "安装依赖: pip install -r requirements.txt"
        fi
    fi

    # 3. 使用系统Python
    if command -v python3 &> /dev/null; then
        echo "🔧 使用系统Python3..."
        PYTHON_CMD="python3"
        return 0
    elif command -v python &> /dev/null; then
        echo "🔧 使用系统Python..."
        PYTHON_CMD="python"
        return 0
    fi

    echo "❌ 未找到可用的Python环境"
    return 1
}

# 设置Python环境
if ! setup_python_env; then
    exit 1
fi

# 检查依赖是否安装
echo "📦 检查依赖..."
if ! ${PYTHON_CMD:-python} -c "import uvicorn" 2>/dev/null; then
    echo "安装依赖中..."
    ${PYTHON_CMD:-python} -m pip install -r requirements.txt
fi

# 启动服务器
echo "🌐 启动API服务器 (http://0.0.0.0:8001)..."
echo "📖 API文档: http://0.0.0.0:8001/docs"
${PYTHON_CMD:-python} -m uvicorn app.main:app --host 0.0.0.0 --port 8001
